<?php
/**
 * memcached缓存插件，需服务器环境支持
 * 
 * @package Cache
 */
class CMemcache {
	private static $cache = null;
	private static $config = array();

	
	/**
	 * 载入
	 *
	 * @param bool $connect
	 * @return PW_Memcache
	 */
	public static function init(array $config) {
		self::isUseable();
		self::$cache = new Memcache;			
		foreach ($config as $v) {
			self::$cache->addServer($v['host'], $v['port']);
		}
	}
	
	function addServer($host,$port) {
		self::$config[] = array('host'=>$host, 'port'=>$port);
	}
	
	public static function close() {
		self::$cache->close();			
	}

	/**
	 * 清空memcache缓存
	 *
	 * @return bool
	 */
	public static function flush() {
		return self::$cache->flush();
	}

	/**
	 * 删除
	 *
	 * @param string $key
	 * @return bool
	 */
	public static function delete($key) {
		if(is_array($key)){
			foreach($key as $k){
				self::$cache->delete(self::getKey($k));
			}
		}else{
			self::$cache->delete(self::getKey($key));
		}
	}

	/**
	 * 设置
	 *
	 * @param string $key 缓存KEY
	 * @param string $value
	 * @param int $expire
	 * @return bool
	 */
	public static function set($key, $value, $expire=86400) {
		
		return self::$cache->set(self::getKey($key), $value, MEMCACHE_COMPRESSED, $expire);
	}

	/**
	 * 获取
	 *
	 * @param string|array $keys
	 * @return string|array
	 */
	public static function get($keys) {
		if (!is_array($keys) && !empty($keys))
			return self::$cache->get(self::getKey($keys));
		
		$data = array();
		foreach ($keys as $key) {
			$result = self::$cache->get(self::getKey($key));
			if($result){
				$data[$key] = $result;
			}
		}
		return $data;		
	}

	function getKey($key) {
		return 'mem_'.substr(md5($key), 15, 8);
	}
	
	/**
	 * 获取Memcache实例化对象
	 *
	 * @return object
	 */
	function &getMemcache() {
		if (!is_object(self::$cache)) {
			self::$cache = new Memcache;
		}
		return self::$cache;
	}


	/**
	 * 检查环境是否支持memcache组件
	 *
	 * @return bool
	 */
	function isUseable() {
		if (class_exists('Memcache')) {
			return true;
		}
		exit('Memcache is unuseable!');
	}
	
	
	
	
}
?>